<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

/**
 * 系统操作日志控制器
 * @package App\Http\Controllers\Admin
 */
class SysOperationLogController extends BaseController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 操作日志列表
     */
    public function index(Request $request)
    {
        $pageSize = $request->get('pageSize', 10);
        $query = \App\Models\System\OperationLog::query()->select('*');
        //用户ID
        $userId = $request->input('user_id', 0);
        if ($userId) {
            $query->where('user_id', $userId);
        }
        //用户名
        $userName = $request->get('user_name', '');
        if ($userName) {
            $query->where('user_name', 'like', $userName . '%');
        }
        //路由ID
        $permIds = $request->get('perm_id', []);
        if ($permIds) {
            $query->where('perm_id', array_pop($permIds));
        }
        $timeArea = $request->get('timeArea', []);
        $startTime = !empty($timeArea[0]) ? strtotime($timeArea[0]) : 0;
        $endTime = !empty($timeArea[1]) ? strtotime($timeArea[1]) : 0;
        if (!empty($startTime) && !empty($endTime)) {
            $query->whereBetween('add_time', [$startTime, $endTime]);
        } elseif (!empty($startTime) && empty($endTime)) {
            $query->whereRaw("add_time >= '" . $startTime . "'");
        } elseif (empty($startTime) && !empty($endTime)) {
            $query->whereRaw("add_time <= '" . $endTime . "'");
        }
        $query->orderByDesc('id');
        $rows = $query->paginate($pageSize, ['*'], 'pageNo');
        if ($rows) {
            foreach ($rows as $k => $v) {
                $v['add_time'] = $v['add_time'] ? date('Y-m-d H:i:s', $v['add_time']) : '';
                $v['request_data'] = !empty($v['request_data']) ? var_export($v['request_data'], true) : '';
                $rows[$k] = $v;
            }
        }
        //权限树结构菜单列表
        $permSer = new \App\Services\System\Permission();
        $permList = $permSer->getCachePermList();
        $tree = new \App\Services\Tool\TreeService('perm_id', 'parent_id', 'children');
        $tree->load($permList);
        $treePermList = $tree->deepTree();

        return $this->success('获取成功', [
            'logList' => $rows->items(),
            'total' => $rows->total(),
            'pageNo' => $rows->currentPage(),
            'permList' => $treePermList
        ]);
    }
}
